import {
  Body,
  Controller,
  Logger,
  Post,
  Req,
  UnauthorizedException,
  UseGuards
} from '@nestjs/common'
import {ApiOperation, ApiTags} from '@nestjs/swagger'

import {ApiResult} from '~/common/decorators/api-result.decorator'

// import {UserService} from '../user/user.service'

import {AuthService} from './auth.service'
import {Public} from './decorators/public.decorator'
import {LoginDto} from './dto/auth.dto'
import {LocalGuard} from './guards/local.guard'
import {LoginToken} from './models/auth.model'
// import {CaptchaService} from './services/captcha.service'
import {FastifyRequest} from "fastify";

@ApiTags('Auth - 认证模块')
// @UseGuards(LocalGuard)
@Controller('auth')
export class AuthController {
	private readonly logger = new Logger(AuthController.name)

  constructor(
    private authService: AuthService,
    // private userService: UserService,
    // private captchaService: CaptchaService,
  ) {
  }

  @Post('login')
	@Public()
  @ApiOperation({summary: '登录'})
  @ApiResult({type: LoginToken})
  async login(@Body() dto: LoginDto): Promise<LoginToken> {
    // await this.captchaService.checkImgCaptcha(dto.captchaId, dto.verifyCode)
    try {
      const token = await this.authService.login(dto.code)
      return {token}
    }
    catch (e) {
      throw new UnauthorizedException(e.message ?? '登录失败')
    }
  }

  // @ApiExcludeEndpoint()
  // @Post('register')
  // @ApiOperation({summary: '注册'})
  // async register(@Body() dto: RegisterDto): Promise<void> {
  //   await this.userService.register(dto)
  // }

  @Post('check')
	@Public()
  @ApiOperation({summary: '登录校验'})
  async mpLoginCheck(@Req() request: FastifyRequest) {
    if (!request.accessToken) {
      throw new UnauthorizedException('未登录')
    }

    // 判断token是否过期
    const isValid: boolean = await this.authService.checkAccessToken(request.accessToken)

    if (!isValid) {
      throw new UnauthorizedException('未登录')
    }

    return "已登录"
  }
}
